package com.anxin.common.utils;

import java.util.Locale;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.MessageSource;

import com.alibaba.fastjson.JSON;

public class JsonResult {
	private final Log log = LogFactory.getLog(getClass());

	public final static JsonResult ERROR_RESULT = new JsonResult(false);

	private String errorCode="0";
	private String errorMessage;
	private Object response;

	public static JsonResult getResult(Object data) {
		JsonResult jsonResult = new JsonResult();
		jsonResult.setResponse(data);
		return jsonResult;
	}

	public static JsonResult error(String errorCode, MessageSource messageSource, Object... params) {
		JsonResult jsonResult = new JsonResult();
		jsonResult.setErrorCode(errorCode);
		jsonResult.setErrorMessage(messageSource.getMessage(errorCode, params, errorCode, Locale.SIMPLIFIED_CHINESE));
		return jsonResult;
	}

	public JsonResult() {
		super();
	}

	public JsonResult(boolean success) {
		super();
		if (!success) {
			this.errorCode = "0101";
		}

	}

	public String getErrorCode() {
		return errorCode;
	}

	public void setErrorCode(String errorCode) {
		this.errorCode = errorCode;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}

	public Object getResponse() {
		return response;
	}

	public void setResponse(Object response) {
		this.response = response;
	}

	@Override
	public String toString() {
		String json = JSON.toJSONString(this);
		if (StringUtils.isEmpty(json)) {
			log.error("JsonResult to Json String error.");
			json = "{\"errCode\":\"serialize.error\",\"message\":\"serialize.error\",\"response\":\"\"}";
		}
		return json;
	}

	public void setError(String errorCode, MessageSource messageSource, Object... params) {
		this.setErrorCode(errorCode);
		this.setErrorMessage(messageSource.getMessage(errorCode, params, errorCode, Locale.SIMPLIFIED_CHINESE));
	}

}
